﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 普通追踪器，可以以曲线运动的方式追踪到终点目标
/// </summary>
public class BhvTrackTo : MonoBehaviour
{
    [SerializeField] private Transform target;
    public float speed = 30;    //飞行速度
    public float maxSpeed = 30f;
    public float accel = 1f;//加速度，随着时间加速
    public float radian = 1;    //弧度

    public Action onHitTarget;
    public Action onCancelTarget;

    public bool mode2d = false;

    private bool isTracking = false;

    public bool IsTracking => isTracking;

    private Vector3 targetPosition = Vector3.zero;

    public void Track(GameObject obj, float speed, float radian)
    {
        target = obj.transform;
        this.speed = speed;
        this.radian = radian;
        isTracking = true;
    }

    public void Track(GameObject obj)
    {
        target = obj.transform;
        isTracking = true;
    }
    public void Track(Transform target)
    {
        target = target.transform;
        isTracking = true;
    }

    public void Stop()
    {
        this.speed = 0f;
        this.target = null;
        isTracking = false;
    }

    public void Track(Vector3 position)
    {
        this.target = null;
        targetPosition = position;
        isTracking = true;
    }

    void Update()
    {
        if (isTracking == false)
            return;

        // 自动解除绑定关系
        if (target && target.gameObject.activeInHierarchy == false)
        {
            target = null;
        }

        if (target == null)
        {
            isTracking = false;
            onCancelTarget?.Invoke();
        }

        Track();
    }

    private void Track()
    {
        if (target)
        {
            targetPosition = target.position;
        }

        var d = Vector3.Distance(transform.position, targetPosition);

        this.speed += accel * Time.deltaTime;
        if (this.speed >= maxSpeed)
        {
            this.speed = maxSpeed;
        }

        if (mode2d)
        {
            transform.up = Vector3.Slerp(transform.up, targetPosition - transform.position, radian / d);
            transform.position += transform.up * speed * Time.deltaTime;
        }
        else
        {
            transform.forward = Vector3.Slerp(transform.forward, targetPosition - transform.position, radian / d);
            transform.position += transform.forward * speed * Time.deltaTime;
        }


        d = Vector3.Distance(transform.position, targetPosition);
        if (d <= 0.5f)
        {
            isTracking = false;
            onHitTarget?.Invoke();
        }


    }

}
